using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class SceneLoader : MonoBehaviour
{
    [Header("存档系统")] public LoadAndSave loadAndSave;
    [Header("Config")] [SerializeField] private float fadeDuration;
    
    [Header("Dependencies")]
    [SerializeField] public Image Mask;
    
    private GameSceneSO currentMainScene; // 当前主场景

    private bool isLoading;
    private bool isFading = false;

    private void Start()
    {
        Mask.color = Color.black;
        Mask.gameObject.SetActive(false);
        // 淡入效果
        StartCoroutine(Fade(1, 0, fadeDuration));
    }

    private IEnumerator LoadScene(GameSceneSO scene)
    {
        // 根据模式选择加载方式
        var operation = scene.sceneReference.LoadSceneAsync();
        yield return operation;

        if (operation.Status == AsyncOperationStatus.Succeeded)
        {
            Scene loadedScene = operation.Result.Scene;
            SceneManager.SetActiveScene(loadedScene); // 设置活动场景
        }
    }

    public void LoadSceneRequest(GameSceneSO targetScene, bool fade = true, bool keepCurrent = false)
    {
        if (isLoading) return;
        StartCoroutine(TransitionScenes(targetScene, fade, keepCurrent));
    }

    private IEnumerator TransitionScenes(GameSceneSO targetScene, bool fade, bool keepCurrent)
    {
        isLoading = true;
        // 淡入
        yield return StartCoroutine(Fade(0, 1, fadeDuration));
    
        Debug.Log("开始保存数据...");
        // 确保保存操作完成
        var saveOperation = loadAndSave.FullSave();
        while (saveOperation.MoveNext()) { yield return null; }
        Debug.Log("数据保存完成");

        // 加载新场景
        yield return StartCoroutine(LoadScene(targetScene));
    
        // 淡出
        yield return StartCoroutine(Fade(1, 0, fadeDuration));
    
        isLoading = false;
    }

    private IEnumerator Fade(float startAlpha, float endAlpha, float duration)
    {
        Debug.Log("渐变跳转");
        Mask.gameObject.SetActive(true);
        float elapsed = 0f;
    
        Color maskColor = Mask.color;
        maskColor.a = startAlpha; // 初始化遮罩透明度
        Mask.color = maskColor;

        isFading = true;
        
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
        
            // 计算当前透明度
            float currentAlpha = Mathf.Lerp(startAlpha, endAlpha, elapsed / duration);
        
            // 更新遮罩透明度
            maskColor.a = currentAlpha;
            Mask.color = maskColor;
        
            yield return null; // 等待下一帧
        }
    
        // 确保结束时达到目标透明度
        maskColor.a = endAlpha;
        Mask.color = maskColor;
    
        // 如果淡入结束，则隐藏遮罩
        if (Mathf.Approximately(endAlpha, 0f)) 
        {
            Mask.gameObject.SetActive(false);
        }
        
        isFading = false;
    }
}